package org.jeecg.modules.hqbaoxiao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.JsonUtils;
import org.jeecg.modules.gudingzichan.entity.Gudingzichan;
import org.jeecg.modules.gudingzichan.service.IGudingzichanService;
import org.jeecg.modules.hqbaoxiao.entity.HqBaoxiao;
import org.jeecg.modules.hqbaoxiao.entity.HqBaoxiaoDetail;
import org.jeecg.modules.hqbaoxiao.mapper.HqBaoxiaoDetailMapper;
import org.jeecg.modules.hqbaoxiao.mapper.HqBaoxiaoMapper;
import org.jeecg.modules.hqbaoxiao.service.IHqBaoxiaoService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.model.TreeSelectModel;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 报销
 * @Author: jeecg-boot
 * @Date:   2020-07-07
 * @Version: V1.0
 */
@Service
@Slf4j
public class HqBaoxiaoServiceImpl extends ServiceImpl<HqBaoxiaoMapper, HqBaoxiao> implements IHqBaoxiaoService, JavaDelegate {


    @Autowired
    private IdentityService identityservice;
    @Autowired
    private RuntimeService runtimeservice;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private HqBaoxiaoDetailMapper hqBaoxiaoDetailMapper;
    @Autowired
    private ISysDepartService sysDepartService;

    @Transactional
    @Override
    public void startFlow(HqBaoxiao hqBaoxiao,LoginUser user) {
        List<SysUser> userList = userService.queryByPost(user.getOrgCode(),"shenpiren");
        if(CollectionUtils.isEmpty(userList)){
            throw new RuntimeException("部门负责人为空");
        }
//        SysDepart depart = this.sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode,user.getOrgCode()));
//        if(StringUtils.isBlank(depart.getOrgBmjb())){
//            throw new RuntimeException("部门级别没有设置");
//        }
        this.baseMapper.insert(hqBaoxiao);
        List<HqBaoxiaoDetail> hqBaoxiaoDetailList = hqBaoxiao.getHqBaoxiaoDetailList();
        if(hqBaoxiaoDetailList!=null && hqBaoxiaoDetailList.size()>0) {
            for(HqBaoxiaoDetail entity:hqBaoxiaoDetailList) {
                //外键设置
                entity.setBaoxiaoId(hqBaoxiao.getId());
                hqBaoxiaoDetailMapper.insert(entity);
            }
        }

        String businesskey = "" + hqBaoxiao.getId();

        identityservice.setAuthenticatedUserId(user.getUsername());

        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("applyUser", user.getUsername());
        variables.put("auditUser",userList.get(0).getUsername());
        variables.put("amount", Float.parseFloat(hqBaoxiao.getAmount()));
//        variables.put("bmjb",depart.getOrgBmjb());
        variables.put("sqlx",hqBaoxiao.getSqlx());
        Model modelData = repositoryService.getModel(hqBaoxiao.getBmjb());
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(modelData.getDeploymentId()).singleResult();

        ProcessInstance instance=runtimeservice.startProcessInstanceById(processDefinition.getId(),businesskey,variables);
        String instanceid=instance.getId();
        hqBaoxiao.setProcessInstanceId(instanceid);
        Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).taskAssignee(user.getUsername()).singleResult();
        hqBaoxiao.setTaskId(task.getId());
        this.baseMapper.updateById(hqBaoxiao);
        taskService.complete(task.getId(),variables);
    }

    @Override
    public void complateTask(LoginUser loginUser,String hezje, String taskId,String processInstanceId, Integer status, String memo) {
//        taskService.claim(taskId,loginUser.getId());
        this.getBaseMapper().update(new HqBaoxiao().setHezje(hezje),new LambdaUpdateWrapper<HqBaoxiao>().eq(HqBaoxiao::getProcessInstanceId,processInstanceId));
        if(StringUtils.isBlank(memo)){
            memo = status == 1?"通过":"驳回";
        }

        Map map = new HashMap(){{
            put("status",status);

        }};
        map.put("memo",memo);
        taskService.addComment(taskId,processInstanceId, JsonUtils.toJsonString(map));

        taskService.complete(taskId,map);
    }

    @Override
    public void applyAgain(HqBaoxiao hqBaoxiao,LoginUser user) {

        Task task = taskService.createTaskQuery().processInstanceId(hqBaoxiao.getProcessInstanceId()).taskAssignee(user.getUsername()).singleResult();
        hqBaoxiao.setTaskId(task.getId());
        this.baseMapper.updateById(hqBaoxiao);

        //1.先删除子表数据
        hqBaoxiaoDetailMapper.deleteByMainId(hqBaoxiao.getId());
        List<HqBaoxiaoDetail> hqBaoxiaoDetailList = hqBaoxiao.getHqBaoxiaoDetailList();
        //2.子表数据重新插入
        if(hqBaoxiaoDetailList!=null && hqBaoxiaoDetailList.size()>0) {
            for(HqBaoxiaoDetail entity:hqBaoxiaoDetailList) {
                //外键设置
                entity.setBaoxiaoId(hqBaoxiao.getId());
                hqBaoxiaoDetailMapper.insert(entity);
            }
        }

        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("status",null);
        variables.put("amount",hqBaoxiao.getAmount());
        taskService.complete(task.getId(),variables);
    }

    @Override
    public IPage<HqBaoxiao> myApplyList(Page<HqBaoxiao> page, LoginUser user, HqBaoxiao hqBaoxiao) {
        return this.baseMapper.myApplyList(page,user,hqBaoxiao);
    }

    @Override
    public IPage<HqBaoxiao> myTodoTasks(Page<HqBaoxiao> page, LoginUser user, HqBaoxiao hqBaoxiao) {
        return this.baseMapper.myTodoTasks(page,user,hqBaoxiao);
    }

    @Override
    public IPage<HqBaoxiao> myDoneTasks(Page<HqBaoxiao> page, LoginUser user, HqBaoxiao hqBaoxiao) {
        return this.baseMapper.myDoneTasks(page,user,hqBaoxiao);
    }
    @Autowired
    IGudingzichanService gudingzichanService;

    @Override
    public void execute(DelegateExecution delegateExecution) {
        System.out.println("触发核减预算余额");

        String busKey = delegateExecution.getProcessInstanceBusinessKey();
        HqBaoxiao baoxiao = this.getBaseMapper().selectById(busKey);
        baoxiao.setBaoxStatus(1);
        this.getBaseMapper().updateById(baoxiao);

        // 如果有资产编号更新固定资产状态为已审批
        String id = baoxiao.getGudzcbh();
        if(id != null) {
            // 新增流程来自报销销模块中的固定资产信息
            // 5代表审批通过
            Gudingzichan gudingzichan = gudingzichanService.getById(id);
            if(gudingzichan != null) {
                gudingzichan.setZichanStatus("5");
                gudingzichanService.updateById(gudingzichan);
                log.info("更新固定资产状态，已审批");
            }
        }
    }

    @Override
    public void delMain(String id) {
        hqBaoxiaoDetailMapper.deleteByMainId(id);
        this.baseMapper.deleteById(id);
    }

    @Override
    public List<TreeSelectModel> kemulistByPid(String orgCode,String pid) {
        return baseMapper.kemuListByPid(orgCode,pid);
    }
}
